import vue from 'vue';
import toastComponent from './Toast';
import { EventEmitter } from 'events';
let event = new EventEmitter();

const ToastConstructor = vue.extend(toastComponent);
let isToastShowing = false;
// 挂载组件
const toastDom = new ToastConstructor({
  el: document.createElement('div'),
  data() {
    return {
      text: '',
      showWrap: false, // 是否显示组件
      showContent: false // 作用:在隐藏组件之前,显示隐藏动画
    };
  },
  methods: {
    show() {
      this.showWrap = true;
      this.showContent = true;
    },
    hide() {
      this.showContent = false;
      setTimeout(() => {
        this.showWrap = false;
      }, 1000);
    }
  }
});
document.body.appendChild(toastDom.$el);
// 定义弹出组件的函数 显示文本 和 显示时间
async function showToast(text, duration = 3000) {
  if (isToastShowing) {
    return new Promise(resolve => {
      event.once('finished', async() => {
        await showToast(text);
        resolve();
      });
    });
  }
  async function keepLongSeconds(s) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, s);
    });
  }
  isToastShowing = true;
  return new Promise(async resolve => {
    toastDom.text = text;
    toastDom.show(); //  淡入 1s
    await keepLongSeconds(2000); // 实际停留时间 1s
    toastDom.hide(); // 淡出1s
    await keepLongSeconds(1000);
    isToastShowing = false;
    event.emit('finished');
    resolve();
  });
}
export default showToast;
